package com.gitee.feizns.dynamic.time;

import java.time.Duration;
import java.time.Instant;
import java.util.Optional;

/**
 * 定时值
 * @author feizns
 * @since 2025/4/11
 */
public class TimedValue<T> {

    /**
     * 值
     */
    private final T value;

    /**
     * 期间
     */
    private final Duration duration;

    /**
     * 缓存时间
     */
    private final Instant cachedTime;

    /**
     * 定时值
     * @param value 值
     * @param duration 期间
     */
    public TimedValue(T value, Duration duration) {
        this.value = value;
        this.duration = duration;
        this.cachedTime = Instant.now();
    }

    /**
     * 创建一个定时值
     * @param value 值
     * @param duration 期间
     * @return {@link TimedValue }<{@link T }>
     */
    public static <T> TimedValue<T> of(T value, Duration duration) {
        return new TimedValue<>(value, duration);
    }

    /**
     * 获取值如果过期跟零
     * @return {@link T }
     */
    public T get() {
        return !isExpired() ? this.value : null;
    }

    /**
     * 获取值如果过期跟选择
     * @return {@link T }
     */
    public Optional<T> getAsOpt() {
        return Optional.ofNullable(get());
    }

    /**
     * 是否是过期
     * @return boolean
     */
    public boolean isExpired() {
        return Instant.now().isAfter(cachedTime.plus(duration));
    }

    /**
     * 新品
     * @return {@link TimedValue }<{@link T }>
     */
    public TimedValue<T> of() {
        return new TimedValue<>(value, duration);
    }

    /**
     * 新品
     * @param duration 期间
     * @return {@link TimedValue }<{@link T }>
     */
    public TimedValue<T> of(Duration duration) {
        return new TimedValue<>(value, duration);
    }

}
